<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>测试页面</title>
</head>
<body>

<div>
    <button id="connect" onclick="connection()">连接</button>
    <button id="close" onclick="closeWebSocket()">关闭连接</button>
    <br>
    <input type="text" id="toMessage" value="" placeholder="发送的消息">
    <button id="send" onclick="sendMessage()">发送</button>
    <br>
    <div id="wsMsg">
        <h3>显示Websocket请求信息：</h3>
    </div>
</div>

<script type="text/javascript">
    //定义webSocket对象
    let websocket = null;

    //定义发送函数
    function connection() {
        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            websocket = new WebSocket("ws://localhost:8888/test/ws/teacherHandler?name=tom");
        } else if ('MozWebSocket' in window) {
            websocket = new MozWebSocket("ws://localhost:8888/test/ws/teacherHandler?name=tom");
        } else {
            websocket = new SockJS("ws://localhost:8888/test/ws/teacherHandler?name=tom");
        }
        //连接发生错误的回调方法
        websocket.onerror = function () {
            let element = document.createElement("p");
            element.textContent = "WebSocket连接发生错误..."
            document.getElementById("wsMsg").appendChild(element)
        }
        //连接成功建立的回调方法
        websocket.onopen = function () {
            let element = document.createElement("p");
            element.textContent = "WebSocket连接成功..."
            document.getElementById("wsMsg").appendChild(element)
        }
        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            let element = document.createElement("p");
            element.textContent = "数据接收成功..." + event.data
            document.getElementById("wsMsg").appendChild(element)
        }
        //连接关闭的回调方法
        websocket.onclose = function () {
            let element = document.createElement("p");
            element.textContent = "WebSocket连接关闭..."
            document.getElementById("wsMsg").appendChild(element)
        }
        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            closeWebSocket();
        }
    }

    //定义发送ws函数
    function sendMessage() {
        //定义发送的数据
        let toMessage = document.getElementById("toMessage").value
        let sendJson = `{"toName":"tom","toMessage":"${toMessage}"}`;
        if (websocket != null) {
            websocket.send(sendJson)
            //写出到信息栏
            let element = document.createElement("p");
            element.textContent = "发送数据：" + sendJson
            document.getElementById("wsMsg").appendChild(element)
        }
    }

    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }
</script>

</body>
</html>